package com.dai.wechat.util;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.xml.parsers.SAXParser;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ParseXmlUtils {

    public static Map<String,String> parseXml(HttpServletRequest request) throws IOException, DocumentException {
        Map<String,String> map = new HashMap<>();
        // 利用dom4j解析XMl文件
        // 获取到文档对象
        InputStream inputStream = request.getInputStream();
        SAXReader saxReader = new SAXReader();
        Document document = saxReader.read(inputStream);
        // 开始解析
        Element rootElement = document.getRootElement();
        List<Element> elements = rootElement.elements();
        // 遍历所有节点
        for (Element element : elements) {
            String name = element.getName();
            String stringValue = element.getText();
            map.put(name, stringValue);
        }
        // 关闭流
        inputStream.close();
        return map;
    }
}
